<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'

// 任务输入组件

const props = defineProps({
  newTaskCategory: {
    type: String,
    required: true
  },
  categories: {
    type: Array<string>,
    required: true
  },
  filteredTasksLength: {
    type: Number,
    required: true
  },
  allSelected: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits(['add-todo', 'update-category', 'update-all-selected'])

const newMessage = ref('')

const handleCategoryChange = (e: Event) => {
  const target = e.target as HTMLSelectElement
  emit('update-category', target.value)
}

const handleKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    addTodo()
  }
}

const addTodo = () => {
  const msg = newMessage.value.trim()
  if (!msg) return
  emit('add-todo', msg)
  newMessage.value = '' 
}

const handleAllSelectedChange = (e: Event) => {
  const target = e.target as HTMLInputElement
  emit('update-all-selected', target.checked)
}
</script>

<template>
  <div class="input-group">
    <label v-if="filteredTasksLength" class="select-all-btn" @click.stop>
      <input 
        type="checkbox" 
        :checked="allSelected" 
        @change="handleAllSelectedChange"
        class="select-all-checkbox" 
      />
      <span class="select-all-text">全选</span>
    </label>

    <input
      type="text"
      class="task-input"
      v-model="newMessage"
      @keydown="handleKeydown"
      placeholder="添加新任务..."
      autocomplete="off"
    />
    <select 
      :value="newTaskCategory"
      @change="handleCategoryChange"
      class="category-select"
    >
      <option v-for="category in categories" :key="category" :value="category">
        {{ category }}
      </option>
    </select>

    <button class="add-btn" @click="addTodo">+</button>
  </div>
</template>